package com.lvmama.service.system.impl;

import java.util.List;
import java.util.stream.Collectors;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.lvmama.common.constants.Constants;
import com.lvmama.common.exception.GlobalException;
import com.lvmama.common.result.CodeMessage;
import com.lvmama.common.result.Result;
import com.lvmama.common.utils.RandomUUIDUtil;
import com.lvmama.dao.rhino.system.MenuDao;
import com.lvmama.dao.rhino.system.RoleMenuDao;
import com.lvmama.pojo.base.Page;
import com.lvmama.pojo.dto.rhino.system.MenuDTO;
import com.lvmama.pojo.dto.rhino.system.MenuQuery;
import com.lvmama.pojo.dto.rhino.system.MenuQueryDTO;
import com.lvmama.pojo.entity.rhino.system.Menu;
import com.lvmama.pojo.entity.rhino.system.RoleMenu;
import com.lvmama.pojo.entity.rhino.system.User;
import com.lvmama.service.system.MenuService;

@Slf4j
@Service
public class MenuServiceImpl implements MenuService {

    @Autowired
    private MenuDao menuDao;
    @Autowired
    private RoleMenuDao roleMenuDao;

    /**
     * 查询菜单
     */
    @Override
    public Result<Page<Menu>> getMenuList(MenuQueryDTO query){
        Page<Menu> pagingMenu = new Page<>();
        int count = menuDao.countMenuList();
        List<Menu> menuList = menuDao.selectMenuList(query);
        pagingMenu.setStart(query.getStart());
        pagingMenu.setResults(count);
        pagingMenu.setLimit(query.getLimit());
        pagingMenu.setPage(query.getPage());
        pagingMenu.setPageNo(query.getPageNo());
        pagingMenu.setRows(menuList);
        pagingMenu.setIsSuccess(true);
        pagingMenu.pageView("/menu/menuList", null);
        return Result.success(pagingMenu);
    }

    /**
     * 查询菜单分页
     *
     * @param query 查询条件
     * @return 分页
     */
    @Override
    public Page<Menu> queryMenuPage(MenuQueryDTO query) {
        log.info("queryMenuPage start. query:{}",
                ToStringBuilder.reflectionToString(query, ToStringStyle.DEFAULT_STYLE));
        Page<Menu> page = new Page<>();
        try {
            int count = menuDao.countMenuList();
            List<Menu> rows = menuDao.selectMenuList(query);
            //设置结果及分页对象
            if (null != rows && !rows.isEmpty()) {
                log.info("queryMenuPage results:{}", count);
                log.info("queryMenuPage rows:{}",
                        ToStringBuilder.reflectionToString(rows, ToStringStyle.DEFAULT_STYLE));
                page.setStart(query.getStart());
                page.setResults(count);
                page.setLimit(query.getLimit());
                page.setPage(query.getPage());
                page.setPageNo(query.getPageNo());
                page.setRows(rows);
                page.setIsSuccess(true);
            }
            //分页展示
            String url = "/menu/menuList.do";
            page.pageView(url, null);
        } catch (Exception e) {
            log.error("queryMenuPage error:{}", e.getMessage(), e);
            page.setError("数据库查询菜单分页失败");
            page.setErrorCode(e.getMessage());
            page.setErrorCode(e.getMessage());
            page.setResults(0);
        }
        log.info("queryMenuPage end.");
        return page;
    }

    /**
     * 通过id查询单个菜单
     *
     * @param id id
     * @return 菜单对象
     */
    @Override
    public Result<Menu> getMenuById(String id) {
        Menu menu = menuDao.queryMenuById(id);
        return Result.success(menu);
    }

    /**
     * 更新菜单
     */
    @Override
    public Result<Boolean> updateMenu(MenuDTO menuDTO){
        menuDao.updateByPrimaryKeySelective(menuDTO);
        return Result.success(true);
    }

    /**
     * 保存
     */
    @Override
    public Result<Boolean> saveMenu(MenuDTO menuDTO){
        String id = RandomUUIDUtil.getRadomUUID();
        menuDTO.setId(id);
        menuDao.insertSelective(menuDTO);
        //保存role_menu
        RoleMenu roleMenu = new RoleMenu();
        roleMenu.setRoleId(Constants.ONE);
        roleMenu.setMenuId(id);
        roleMenuDao.insertSelective(roleMenu);
        return Result.success(true);
    }

    @Override
    public Result<Boolean> deleteMenuById(String id) {
        MenuDTO menuDTO = new MenuDTO();
        menuDTO.setId(id);
        menuDTO.setDelFlag("1");
        menuDao.updateByPrimaryKeySelective(menuDTO);
        return Result.success(true);
    }

    /**
     * 查询已选择过的菜单图标
     *
     * @return 图标String集合
     */
    @Override
    public Result<List<String>> getMenuIcons() {
        MenuQuery example = new MenuQuery();
        example.setFields("icon");
        example.setDistinct(true);
        example.createCriteria().andDelFlagEqualTo(Constants.DEL_FLAG).andIconIsNotNull()
                .andIconNotEqualTo("");
        List<Menu> menus = menuDao.selectByExample(example);
        List<String> icons = menus.stream().map(Menu::getIcon).collect(Collectors.toList());
        return Result.success(icons);
    }

    @Override
    public Result<List<Menu>> getAllMenuListByUser(User user) {
        List<Menu> menus;
        if (user.isAdmin()) {
            MenuQueryDTO query = new MenuQueryDTO();
            menus = menuDao.selectMenuList(query);
        } else {
            menus = menuDao.selectMenuListByUserId(user.getId());
        }

        if (menus == null || menus.isEmpty()) {
            throw new GlobalException(CodeMessage.MENU_EMPTY);
        }
        return Result.success(menus);
    }
}